<template>
  <div>
    <el-card class="card_body">
      <div class="search_top">
        <!--        顶部搜索-->
        <el-form ref="form" :model="searchMemberForm" inline>
          <el-form-item label="会员号">
            <el-input
                maxlength="20"
                prefix-icon="el-icon-user"
                placeholder="请输入会员号"
                @input="searchMember"
                v-model="searchMemberForm.memberNo"
                size="small"
                clearable
            >
            </el-input>
          </el-form-item>
          <el-form-item label="手机号">
            <el-input
                maxlength="11"
                prefix-icon="el-icon-mobile-phone"
                placeholder="请输入手机号"
                @input="searchMember"
                v-model="searchMemberForm.mobile"
                size="small"
                clearable
            >
            </el-input>
          </el-form-item>
          <el-form-item label="会员名称">
            <el-input
                maxlength="20"
                prefix-icon="el-icon-user"
                placeholder="请输入会员名称"
                @input="searchMember"
                v-model="searchMemberForm.memberName"
                size="small"
                clearable
            >
            </el-input>
          </el-form-item>
          <el-form-item label="状态">
            <el-select
                v-model="searchMemberForm.active"
                clearable
                size="small"
                @change="searchMember"
                placeholder="请选择会员状态"
            >
              <el-option label="使用中" value="false"></el-option>
              <el-option label="已禁用" value="true"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="注册时间">
            <el-date-picker type="date" placeholder="选择日期"
                            @change="searchMember"
                            clearable
                            v-model="searchMemberForm.registerTime"
                            format="yyyy 年 MM 月 dd 日"
                            value-format="yyyy-MM-dd"
                            size="mini">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="所属店铺">
            <el-select
                v-model="searchMemberForm.store"
                clearable
                size="small"
                @change="searchMember"
                placeholder="请选择店铺"
            >
              <el-option
                  v-for="(item, index) in storeOptions"
                  :key="index"
                  :label="item.name"
                  :value="item.name"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <div class="body_top">
        <el-button size="small" type="primary" @click="searchMember">查询</el-button>
        <el-button size="small" type="success" @click="searchReset">重置</el-button>
        <el-button size="small" type="primary" @click="clickHandler('1')"><i class="el-icon-plus"></i> 新增会员</el-button>
      </div>


      <!--        总结会员数量-->
      <div class="content_body">
        <div class="tag_mark">
          <el-descriptions class="margin-top" :column="10" size="small">
            <el-descriptions-item v-for="(item,index) in memberGroup" :key="index"  :label="item.name">{{ item.count }}</el-descriptions-item>
          </el-descriptions>
        </div>



<!--        表格展示-->
        <div class="table_body">
          <template>
            <el-table
                stripe
                size="mini"
                :header-cell-style="{ background: '#ecf5ff', color: '#606266' }"
                :data="tableData"
                border
                style="width: 100%">
              <el-table-column min-width="50" prop="id" label="ID" width="50">
              </el-table-column>

              <el-table-column
                  prop="member_no"
                  label="会员号">
              </el-table-column>
              <el-table-column
                  prop="member_name"
                  label="会员名称">
              </el-table-column>
              <el-table-column
                  prop="mobile"
                  label="手机号"
                  min-width="130">
              </el-table-column>
              <el-table-column
                  prop="store"
                  label="所属店铺"
                  min-width="100">
              </el-table-column>
              <el-table-column
                  prop="balance"
                  align="center"
                  label="余额">
                <template slot-scope="scope">
                  <div style="display: flex; flex-direction: column; align-items: center;">
                    <span>{{ scope.row.balance }}</span>
                    <el-button
                        type="text"
                        icon="el-icon-wallet"
                        size="mini"
                        @click="openRecharge(scope.row)"
                        style="margin-top: 5px">充值</el-button>
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                  prop="register_time"
                  min-width="150"
                  label="注册时间">
              </el-table-column>
              <el-table-column
                  prop="member_name"
                  min-width="100"
                  align="center"
                  label="状态">
                <template slot-scope="scope">
                  <el-tag size="mini" effect="dark" type="success" v-if="scope.row.active">使用中</el-tag>
                  <el-tag size="mini" effect="dark" type="info" v-else>已禁用</el-tag >
                </template>
              </el-table-column>
              <el-table-column
                  label="备注："
                  min-width="130"
                  prop="remark">
              </el-table-column>
              <el-table-column fixed="right" width="250" label="操作" align="center">
                <template slot-scope="scope">
                  <el-button
                      type="text"
                      icon="el-icon-edit"
                      size="mini"
                      @click="openEdit(scope.row)">修改</el-button>
                  <el-button
                      type="text"
                      icon="el-icon-delete"
                      size="mini"
                      @click="openDelete(scope.row)">删除</el-button>
                  <el-button
                      type="text"
                      icon="el-icon-delete"
                      size="mini"
                      v-if="scope.row.active"
                      @click="openDeleteActive(scope.row)">禁用账号</el-button>
                  <el-button
                      type="text"
                      icon="el-icon-check"
                      size="mini"
                      v-else
                      @click="openActive(scope.row)">解封账号</el-button>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </div>
      </div>
      <!--      底部分页器-->
      <div class="body_paging">
        <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="curPage"
            :page-sizes="[8, 15, 20, 30]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
        >
        </el-pagination>
      </div>
    </el-card>


<!--    单个新增会员表单-->
    <el-dialog
        title="新增会员"
        :visible.sync="openAddDrawer"
        width="50%"
        @open="handleDialogOpen">
      <el-form class="form_item" :rules="addMemberRules" :model="addMemberForm" ref="addMemberForm" label-width="100px">
        <el-form-item label="会员名：" prop="member_name" clearable >
          <el-input v-model="addMemberForm.memberName" placeholder="请输入会员名称"></el-input>
        </el-form-item>
        <el-form-item label="所属店铺">
          <el-select
              v-model="addMemberForm.store"
              clearable
              size="small"
              placeholder="请选择店铺"
          >
            <el-option
                v-for="(item, index) in storeOptions"
                :key="index"
                :label="item.name"
                :value="item.name"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="注册时间：" prop="register_time" clearable>
          <el-date-picker type="date" placeholder="选择日期"   size="small" v-model="addMemberForm.registerTime"
                          format="yyyy 年 MM 月 dd 日"  value-format="yyyy-MM-dd"style="width: 100%;"></el-date-picker>
        </el-form-item>
        <el-form-item label="会员号：" prop="member_no">
          <el-input v-model="addMemberForm.memberNo" placeholder="会员号将自动生成" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="手机号：" prop="mobile" clearable>
          <el-input v-model="addMemberForm.mobile" maxlength="11" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="余额：" prop="balance" clearable>
<!--          <el-input v-model.number="addMemberForm.balance"  placeholder="请输入会员余额"></el-input>-->
          <el-input-number
              v-model="addMemberForm.balance"
              :min="0"
              :precision="2"
              :step="10"
              :value=0.0  
              placeholder="请输入会员余额">
          </el-input-number>
        </el-form-item>
        <el-form-item label="会员状态：" prop="active" clearable>
          <el-radio-group v-model="addMemberForm.active">
            <el-radio :label="true">使用中</el-radio>
            <el-radio :label="false">已禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注信息：" prop="remark">
          <el-input
              type="textarea"
              :rows="3"
              placeholder="请输入备注信息"
              v-model="addMemberForm.remark">
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button size="small" type="primary" @click="addMember">新  增</el-button>
          <el-button size="small" @click="openAddDrawer=false" style="margin-left: 20px">取  消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>


<!--    修改会员信息表单-->
    <el-dialog
        title="修改会员信息"
        :visible.sync="openUpdateDrawer"
        width="50%">
      <el-form class="form_item" :rules="addMemberRules" :model="updateMemberForm" label-width="100px">
        <el-form-item label="会员名：" prop="member_name" clearable >
          <el-input v-model="updateMemberForm.memberName" placeholder="请输入会员名称"></el-input>
        </el-form-item>
        <el-form-item label="所属店铺">
          <el-select
              v-model="updateMemberForm.store"
              clearable
              size="small"
              placeholder="请选择店铺"
          >
            <el-option
                v-for="(item, index) in storeOptions"
                :key="index"
                :label="item.name"
                :value="item.name"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="注册时间：" prop="register_time" clearable>
          <el-date-picker type="date" placeholder="选择日期"   size="small" v-model="updateMemberForm.registerTime"
                          format="yyyy 年 MM 月 dd 日" value-format="yyyy-MM-dd" style="width: 100%;"></el-date-picker>
        </el-form-item>
        <el-form-item label="会员号：" prop="member_no">
          <el-input v-model="updateMemberForm.memberNo" placeholder="请输入会员号"></el-input>
        </el-form-item>
        <el-form-item label="手机号：" prop="mobile" clearable>
          <el-input v-model="updateMemberForm.mobile" maxlength="11" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="余额：" prop="balance" clearable>
<!--          <el-input v-model.number="updateMemberForm.balance"  placeholder="请输入会员余额"></el-input>-->
          <el-input-number
              v-model="updateMemberForm.balance"
              :min="0"
              :precision="2"
              :step="10"
              :value=0
              placeholder="请输入会员余额">
          </el-input-number>
        </el-form-item>
        <el-form-item label="会员状态：" prop="active" clearable>
          <el-radio-group v-model="updateMemberForm.active">
            <el-radio :label="true">使用中</el-radio>
            <el-radio :label="false">已禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注信息：" prop="remark">
          <el-input
              type="textarea"
              :rows="3"
              placeholder="请输入备注信息"
              v-model="updateMemberForm.remark">
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button size="small" type="primary" @click="updateMemberBtn">更  新</el-button>
          <el-button size="small" @click="openUpdateDrawer=false" style="margin-left: 20px">取  消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

<!--    会员余额充值表单-->
    <el-dialog
        title="会员充值"
        :visible.sync="rechargeDialogVisible"
        width="50%">
      <el-form :model="rechargeForm" :rules="rechargeRules" ref="rechargeForm" label-width="100px">
        <el-form-item label="会员名称：" prop="memberName">
          <el-input v-model="rechargeForm.memberName" disabled></el-input>
        </el-form-item>

        <el-form-item label="手机号：" prop="mobile">
          <el-input v-model="rechargeForm.mobile" disabled></el-input>
        </el-form-item>

        <el-form-item label="当前余额：" prop="currentBalance">
          <el-input v-model.number="rechargeForm.currentBalance" disabled></el-input>
        </el-form-item>

        <el-form-item label="变更类型：" prop="changeType">
          <el-radio-group v-model="rechargeForm.changeType">
            <el-radio :label="1">增加</el-radio>
            <el-radio :label="-1">扣减</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="变更金额：" prop="amount">
          <el-input-number
              v-model.number="rechargeForm.amount"
              :min="0"
              :precision="2"
              :step="10"
              :value=0
              placeholder="请输入变更金额">
          </el-input-number>
        </el-form-item>

        <el-form-item label="备注信息：" prop="remark">
          <el-input
              type="textarea"
              :rows="3"
              placeholder="请输入备注信息"
              v-model="rechargeForm.remark">
          </el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitRecharge">操 作</el-button>
          <el-button @click="rechargeDialogVisible = false">取 消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

  </div>
</template>

<script>
import {
  addMemberAPI,
  updateMemberAPI,
  getMemberCountAPI,
  getMemberListAPI,
  deleteMember,
  inactiveMemberAPI,
  activeMemberAPI,
  rechargeMemberAPI
} from "@/api/member/member";



export default {
  name: "memberManager",
  data() {
    return {
      curPage: 1,
      pageSize: 8,
      total: 0,
      // openDrawer: false,
      rechargeDialogVisible: false,
      openAddDrawer: false,
      openUpdateDrawer: false,
      storeOptions: [
        { id: '1', name: '平步青云鞋行' },
        { id: '0', name: '花花小店' }
        // 可以根据实际需求添加更多状态
      ],
      memberGroup:[],
      searchMemberForm: {
        memberNo: '',
        mobile: '',
        memberName: '',
        active: '',
        registerTime: '',
        store: '',
        pageNum: this.curPage,
        pageSize: this.pageSize
      },
      addMemberForm: {
        memberNo: '',
        mobile: '',
        memberName: '',
        balance:0.0,
        active: '',
        registerTime: '',
        store: '',
        remark: '',
      },
      addMemberRules:{
        store: [{ required: true, message: '请选择所属店铺', trigger: 'change'},],
        memberNo: [{ required: true, message: '请输入会员号', trigger: 'blur'},],
        mobile: [
          {required: true, message: "请输入手机号", trigger: "blur"},
          {min: 11, max: 11, message: "长度11位手机号", trigger: "blur"},
        ],
        memberName: [
          {required: true, message: "请输入会员名", trigger: "blur"},
          {min: 1, max: 15, message: "长度在 1 到 15 个字符", trigger: "blur", },
        ],
        active: [{ required: true, trigger: "blur"},],
        registerTime: [{ required: true, value: '请输入会员注册时间', trigger: 'change'},],
        balance: [
          { required: true, message: '请输入会员余额', trigger: 'blur' },
          { type: 'number', message: '会员余额必须为数字' },
          { validator: (rule, value, callback) => {
              if (value < 0) {
                callback(new Error('余额必须大于 0'));
              } else {
                callback();
              }
            },
            trigger: 'blur'
          }
        ]
      },

      updateMemberForm: {
        id: null,
        memberNo: '',
        mobile: '',
        memberName: '',
        balance:0.0,
        active: '',
        registerTime: '',
        store: '',
        remark: '',
      },
      rechargeForm: {
        id: null,
        memberName: '',
        mobile: '',
        currentBalance: 0.0,
        changeType: 1,
        amount: 0,
        remark: ''
      },
      rechargeRules: {
        amount: [
          { required: true, message: '请输入变更金额', trigger: 'blur' },
          { type: 'number', message: '金额必须为数字' }
        ],
        changeType: [
          { required: true, message: '请选择变更类型', trigger: 'change' }
        ]
      },

      headers: {
        Authorization: window.localStorage.getItem('cust-token') // 从cookie里获取token，并赋值  Authorization ，而不是token
      },
      tableData: [
        {
          date: '2016-05-03',
          name: '王小虎',
          address: '上海市普陀区金沙江路 1516 弄'
        }
      ]
    }
  },
  created() {
    this.getMemberCount()
    this.searchMember ()
  },
  methods: {
    // /** 获取店铺分类统计会员信息 */
    getMemberCount (){
      getMemberCountAPI().then(res =>{
        this.memberGroup = res
      }).catch(e =>{
        this.$message.error(e.message)
      })
    },

    // 生成会员号
    generateMemberNo() {
      const now = new Date()
      const year = now.getFullYear()
      const month = String(now.getMonth() + 1).padStart(2, '0')
      const day = String(now.getDate()).padStart(2, '0')
      const random = Math.floor(Math.random() * 10000).toString().padStart(4, '0')

      return `${year}${month}${day}${random}`
    },

    // 打开新增会员对话框时的处理
    handleDialogOpen() {
      this.addMemberForm.memberNo = this.generateMemberNo()
    },


    // 打开充值弹窗
    openRecharge(row) {
      this.rechargeForm.id = row.id
      this.rechargeForm.memberName = row.member_name
      this.rechargeForm.mobile = row.mobile
      this.rechargeForm.currentBalance = row.balance
      this.rechargeForm.amount = 0
      this.rechargeForm.changeType = 1
      this.rechargeForm.remark = ''
      this.rechargeDialogVisible = true
    },
    // 提交充值
    submitRecharge() {
      this.$refs.rechargeForm.validate((valid) => {
        if (valid) {
          // 这里添加充值的接口调用
          const newBalance = (
          parseFloat(this.rechargeForm.currentBalance) +
          parseFloat(this.rechargeForm.changeType) *
          parseFloat(this.rechargeForm.amount)).toFixed(2);  // 保留两位小数
          const params = {
            // ...this.rechargeForm,
            id: this.rechargeForm.id,
            mobile: this.rechargeForm.mobile,
            // final_amount: this.rechargeForm.changeType * this.rechargeForm.amount,
            newbalance: parseFloat(newBalance),
            remark: this.rechargeForm.remark
          }
          // 调用充值接口
          rechargeMemberAPI(params)
              .then(res => {
                this.$message({
                  type: 'success',
                  message: "会员余额充值操作成功！"
                });
                this.rechargeDialogVisible = false;
                this.searchMember(); // 刷新表格数据，
              })
              .catch(e => {
                this.$message.error('充值操作失败');
              });
        }
      });
    },




    /** 编辑内容 */
    openEdit (item){
      this.updateMemberForm.id = item.id
      this.updateMemberForm.mobile = item.mobile
      this.updateMemberForm.memberNo = item.member_no
      this.updateMemberForm.balance = item.balance
      this.updateMemberForm.store = item.store
      this.updateMemberForm.active = item.active
      this.updateMemberForm.registerTime = item.register_time
      this.updateMemberForm.memberName = item.member_name
      this.openUpdateDrawer = true
    },
    /** 更新会员信息*/
    updateMemberBtn(){
      updateMemberAPI(this.updateMemberForm).then(res =>{
        this.$message.success("会员信息更新成功！")
        this.searchMember()
        this.openUpdateDrawer = false
      }).catch(e=>{
        this.$message.error(e.message)
      })
    },
    /** 删除会员 */
    openDelete(data){
      this.$confirm('此操作将永久删除此会员, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let params={
          id: data.id
        }
        deleteMember(params).then(res => {
          this.$message({
            type: 'success',
            message: "删除操作成功！"
          });
          this.searchMember()

          this.getMemberCount()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除此会员'
        });
      });
    },

    clickHandler(i) {
      switch (i) {
        case '1':
          this.openAddDrawer = true;
          break
        default:
          console.log('嘿嘿')
      }

    },
    /** 清除搜索条件 */
    searchReset() {
      this.searchMemberForm.memberNo = ''
      this.searchMemberForm.mobile = ''
      this.searchMemberForm.memberName = ''
      this.searchMemberForm.active = ''
      this.searchMemberForm.registerTime = ''
      this.searchMemberForm.store = ''
      this.searchMember()
    },
    /** 搜索会员列表 */
    searchMember () {
      let params = {
        memberNo: this.searchMemberForm.memberNo,
        mobile: this.searchMemberForm.mobile,
        memberName: this.searchMemberForm.memberName,
        active: this.searchMemberForm.active,
        registerTime: this.searchMemberForm.registerTime,
        store: this.searchMemberForm.store,
        pageNum: this.curPage,
        pageSize: this.pageSize
      }
      getMemberListAPI(params).then(res =>{
        this.tableData = res.list
        this.total = res.total
      })
    },
    /** 点击添加会员 */
    addMember () {
      this.$refs['addMemberForm'].validate((valid) => {
        if (valid) {
          addMemberAPI(this.addMemberForm).then(res=>{
            this.openAddDrawer = false
            this.searchMember()
            this.getMemberCount()
            this.$message.success("创建新会员成功！")
            this.addMemberForm.memberName = ""
            this.addMemberForm.memberNo = ""
            this.addMemberForm.mobile = ""
            this.addMemberForm.balance = ""
            this.addMemberForm.registerTime = ""
            this.addMemberForm.store = ""
            this.addMemberForm.active = ""
          }).catch(e=>{
            this.$message.error(e.message)
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });

    },

    /** 页大小变化激活事件 */
    handleSizeChange(e) {
      this.pageSize = e
      this.searchMember()
    },
    /** 页码变化激活事件 */
    handleCurrentChange(e) {
      this.curPage = e
      this.searchMember()
    },
    /** 会员账号激活*/
    openActive(data){
      let params={
        uid: data.id
      }
      activeMemberAPI(params).then(res => {
        this.$message({
          type: 'success',
          message: "会员账号激活操作成功！"
        });
        this.searchMember()
      }).catch(e=>{
        this.$message.error(e.message)
      })
    },
    /** 禁用会员操作 */
    openDeleteActive(data){
      this.$confirm('此操作将永久禁用此会员用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let params={
          uid: data.id
        }
        inactiveMemberAPI(params).then(res => {
          this.$message({
            type: 'success',
            message: "禁用会员操作成功！"
          });
          this.searchMember()
        }).catch(e=>{
          this.$message.error(e.message)
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消禁用用户'
        });
      });
    }


  }
}
</script>

<style scoped lang="scss">
.el-card.is-always-shadow, .el-card.is-hover-shadow:focus, .el-card.is-hover-shadow:hover {
  box-shadow: none;
}

.content_body {
  margin-top: 10px;
  height: 100%;
}

.tag_mark {
  margin-top: 10px;
}

::v-deep .el-drawer__body {
  background: #F5F5F5 !important;
}

.drawer_top {
  margin: 10px 30px 20px 20px;
}
.body_paging {
  display: flex;
  justify-content: end;
  padding-top: 10px;
}
.top_title {
  font-size: 19px;
  font-weight: bold;
  padding-bottom: 10px;
  margin-bottom: 5px;
  border-bottom: 1px solid #ffffff;
}

.form_item {
  margin-left: 20px;
  margin-right: 30px;
}

.top_mark {
  height: 40px;
  display: flex;
  background-color: #fff5ed;
  align-items: center;
  border-radius: 2px;
  margin-bottom: 12px;
  padding-left: 10px;
}

.el-icon-warning {
  color: #f67207;
}

.mark_detail {
  line-height: 22px;
  color: #f67207;
  margin-left: 8px;
  font-size: 14px;
}

::v-deep .el-upload.el-upload--text {
  height: 100px !important;

  .el-upload-dragger {
    width: 100%;
    //height: 100px !important;
  }

  width: 100%;
}
</style>
